﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace z.Controllers {
	[z.Filters.InitializeSimpleMembership]
	public class MessengerController : Controller {
		public ActionResult Index() {
			return View();
		}
		public ActionResult Administer(int ID) {
			var m = App.db.Occasions.Where(x => x.ID == ID).Single();
			return View("Table",m);
		}
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Add(int ID) {
			var m = new m.db.Messenger();
			m.Occasion_ID = ID;
			return PartialView("_Row", m);
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Delete(int ID) {
			var m = App.db.Messengers.Where(x => x.ID == ID).Single();
			App.db.Messengers.Remove(m);
			App.db.SaveChanges();
			WebSocketController.SendMessenger("Messenger," + m.ID);
			return PartialView("Null");
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Edit(m.db.Messenger In) {
			App.resetDB();
			var isAdd = App.db.Messengers.Where(x => x.ID == In.ID).Count() == 0;
			var m = isAdd ? App.db.Messengers.Add(new m.db.Messenger())
				: App.db.Messengers.Where(x => x.ID == In.ID).Single();
			m.Text = System.Web.HttpUtility.HtmlDecode(In.Text);
			m.Occasion_ID = In.Occasion_ID;
			if (ModelState.IsValid) {
				try {
					App.db.SaveChanges();
				} catch (Exception ex) {
					return null;
				}
			}
			WebSocketController.SendMessenger("Messenger," + m.ID);
			return PartialView("_Row", m);
		}
		[Authorize(Roles = "Mod,Admin")]
		public ActionResult _Show(int ID) {
			var m = App.db.Messengers.Where(x => x.ID == ID).Single();
			return PartialView("_Row", m);
		}
		public ActionResult Dialog() {
			return View();
		}
	}
}
